/**
 *  2018-6-23
 *  email:nur01@qq.com
 */
import React, {Component} from 'react'
import {
    Animated,
    AsyncStorage,
    DeviceEventEmitter,
    Image,
    LayoutAnimation,
    ListView,
    NativeModules,
    RefreshControl,
    StatusBar,
    StyleSheet,
    Text,
    TouchableOpacity,
    View
} from "react-native";
import StyleUtils from "../../res/styles/StyleUtils";
import ViewUtils from "../../utils/ViewUtils";
import IparNetwork, {SERVER_TYPE} from "../../httpUtils/IparNetwork";
import {StatusBarTextStyle} from "../../custom/Navigation";
import SlideMenu from "../../menu/SlideMenu";
import CommonUtils from "../../common/CommonUtils";

export default class SelectCountryPage extends Component {

    constructor(props) {
        super(props);
        let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});

        this.requestNetwork = new IparNetwork();

        this.state = {
            fadeAnim: new Animated.Value(0),
            isOpen: true,
            loading: false,
            isFirst: false,
            dataSource: ds,
        };
    }


    /**
     * 动画open&&close
     */
    startAnimation() {
        let animValue = 300;
        if (!this.state.isOpen) {
            animValue = 0;
        }
        Animated.timing(       // 随时间变化而执行的动画类型
            this.state.fadeAnim,   // 动画中的变量值
            {
                toValue: animValue,   // 透明度最终变为1，即完全不透明
                duration: 500, // 动画时间
            }
        ).start();

        this.setState({
            isOpen: !this.state.isOpen
        })
    }


    componentDidMount() {

        //是否第一次打开app
        AsyncStorage.getItem('country_id', (error, result) => {
            if (result === null) {//第一次打开app
                this.setState({
                    isFirst: true,
                });
            }
        });


        this.onLoadData();
    }


    /**
     * 获取国家信息
     * @param url
     */
    onLoadData() {
        this.showLoading(true);

        this.requestNetwork.getRequest(SERVER_TYPE.logistics + 'region?',)// 'lang=EN'
            .then((result) => {
                this.updateData(result)
            })
            .catch((error) => {
                this.showLoading(false);
            })
    }

    updateData(data) {
        this.showLoading(false);
        this.setState({
            dataSource: this.state.dataSource.cloneWithRows(data)
        })
    }


    /**
     * 更新  loading
     * @param isLoading
     */
    showLoading(isLoading) {
        this.setState({
            loading: isLoading,
        });
    }

    /**
     * 初始化
     * */
    render() {
        return (
            <View style={[StyleUtils.flex, {backgroundColor: 'black'}]}>

                <Image source={require('../../res/images/ic_test_bg.jpg')} style={styles.backgroundImage}/>

                {/*status*/}
                <StatusBar
                    translucent={true}
                    backgroundColor={'transparent'}
                    barStyle={StatusBarTextStyle.white}
                />

                {/*box*/}
                <View style={[StyleUtils.center, {height: '100%', padding: 16}]}>

                    {/*top item*/}

                    {ViewUtils.getButtunMenu('SELECT YOUR COUNTRY', () => this.startAnimation())}

                    <Animated.View                            // 可动画化的视图组件
                        style={[StyleUtils.center, {
                            ...this.props.style,
                            height: this.state.fadeAnim,          // 将透明度指定为动画变量值
                            width: '100%',
                        }]}>
                        <ListView
                            refreshing={true}
                            style={{width: '100%', height: '100%', backgroundColor: 'rgba(0,0,0,0.15)'}}
                            dataSource={this.state.dataSource}
                            renderRow={(rowData) => this.renderRow(rowData)}
                            refreshControl={
                                <RefreshControl
                                    tintColor={'white'}
                                    refreshing={this.state.loading}
                                    onRefresh={() => this.onLoadData()}
                                />
                            }
                        />
                    </Animated.View>


                    {/*bottom item*/}
                    {ViewUtils.getButton('SELECT YOUR COUNTRY', () => this.startAnimation())}
                </View>


            </View>
        )
    }


    /**
     * 跳页面
     */
    startPage(data) {
        //把国家的数据缓存到本地
        new CommonUtils().saveCountryData(data);

        const {navigator} = this.props;
        navigator.resetTo({
            component: SlideMenu,
            name: 'SlideMenu',
            params: {
                ...this.props,
                isFirst: this.state.isFirst,
            }
        });
    }


    /**
     * 初始化list view的items
     *
     * @param rowData
     * @returns {*}
     */
    renderRow(rowData) {
        return (
            <TouchableOpacity
                key={rowData}
                onPress={() => this.startPage(rowData)}
                style={{padding: 4}}>
                <Text style={[StyleUtils.title, StyleUtils.smallFont, {textAlign: 'center', color: 'white',}]}>
                    {rowData.name.toUpperCase()}
                </Text>
            </TouchableOpacity>
        )
    }


}

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    backgroundImage: {
        left: 0,
        right: 0,
        top: 0,
        bottom: 0,
        width: '100%',
        height: '100%',
        resizeMode: 'cover',
        position: 'absolute',
    }
});